﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ABC.Business.Models;
using ABC.Core.Configuration;

namespace ABC.Business.Filters
{
    public class AdminAuthorizeAttribute :  AuthorizeAttribute       
    {
        private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus)
        {
            validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext != null && AuthorizeCore(filterContext.HttpContext))
            {
                var rosModel = IoC.Resolve<RosModel>();
                if (!rosModel.GetEntityValue<bool>(filterContext.HttpContext.User.Identity.Name, "ИмеетсяДоступВАдминку"))
                {
                    var urlHelper = new UrlHelper(filterContext.RequestContext);
                    filterContext.Result = new RedirectResult(urlHelper.Action("Index", "My"));
                }
                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null); 
            }
            else
            {
                HandleUnauthorizedRequest(filterContext);
            }
        }
    }
}
